<template>
  <view
    class="custom-affix"
    :style="{ right: right + 'px', bottom: bottom + 'px' }"
    @touchstart="touchstart"
    @touchmove="touchmove"
    @touchend="touchend"
  >
    <uni-icons :type="icon" :color="color" size="24" @click="onClick"></uni-icons>
  </view>
</template>

<script>
export default {
  props: {
    icon: {
      type: String,
      default: "plusempty",
    },
    color: {
      type: String,
      default: "#303133",
    },
  },
  data() {
    return {
      items: [],
      isDrag: false,
      startX: 0,
      startY: 0,
      defaultRight: 50,
      defaultBottom: 40,
      right: this.defaultRight,
      bottom: this.defaultBottom,

      // 拖拽范围
      minBottom: 20,
      maxBttom: 400,
      minRight: 20,
      maxRight: 200,
    };
  },

  mounted() {
    this.maxRight = uni.getSystemInfoSync().windowWidth - this.minRight * 3;
    this.maxBttom = uni.getSystemInfoSync().windowHeight - this.minBottom * 3;
  },
  methods: {
    onClick(e) {
      this.$emit("onClick", e);
    },
    touchstart(e) {
      this.isDrag = true;
      const { clientX, clientY } = e.changedTouches[0];
      this.startX = clientX;
      this.startY = clientY;
    },
    touchmove(e) {
      const { clientX, clientY } = e.changedTouches[0];
      const deltaX = this.defaultRight + this.startX - clientX;
      const deltaY = this.defaultBottom + this.startY - clientY;

      if (deltaX > this.minRight && deltaX < this.maxRight) {
        this.right = deltaX;
      }

      if (deltaY > this.minBottom && deltaY < this.maxBttom) {
        this.bottom = deltaY;
      }
    },
    touchend() {
      this.startX = 0;
      this.startY = 0;
      this.defaultRight = this.right;
      this.defaultBottom = this.bottom;
    },
  },
};
</script>

<style>
.custom-affix {
  right: 40px;
  bottom: 40px;
  z-index: 1000;
  position: fixed;
  background-color: #fff;
  border-radius: 50%;
  padding: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  cursor: pointer;
}
</style>
